package com.fruit.controller.wap.account;

import com.fruit.controller.base.BaseController;
import com.fruit.pojo.BaseDTO;
import com.fruit.pojo.Page;
import com.fruit.pojo.user.UserReal;
import com.fruit.sdk.account.AccountManager;
import com.fruit.sdk.account.NoticeManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author joe
 * @version 2017.12.12 10:06
 */
@Slf4j
@Controller
@RequestMapping(value = "/wap/account")
public class AccountWapController extends BaseController {
    @Autowired
    private AccountManager accountManager;
    @Autowired
    private NoticeManager noticeManager;


    /**
     * 获取指定用户的钱包
     *
     * @param uid 用户id
     * @return 用户钱包，包含佣金和余额
     */
    @RequestMapping(value = "getUserAccount", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public BaseDTO<AccountManager.Account> getUserAccount(@SessionAttribute("userId") int uid) {
        log.info("获取用户{}的钱包", uid);

        try {
            AccountManager.Account account = accountManager.getUserAccount(uid);
            log.debug("用户{}的钱包为：{}", uid, account);
            return BaseDTO.buildSuccess(account);
        } catch (Exception e) {
            log.error("获取用户{}的钱包出错", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 查询指定月份账单或者明细
     *
     * @param date     指定月份，格式为：yyyy-MM，传入空值或者不传表示查询所有
     * @param uid      用户ID
     * @param pageNo   分页页码，从0开始
     * @param size     分页大小
     * @param isDetail 是否是查询明细，true为查询明细，false为查询账单
     * @return 指定月份账单
     */
    @RequestMapping(value = "getBill", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public BaseDTO<Page<AccountManager.Commission>> getBill(String date, @SessionAttribute("userId")
            long uid,
                                                            int pageNo,
                                                            int size,
                                                            boolean isDetail) {
        log.info("获取用户{}的{}月份的账单，参数为：{}：{}：{}", uid, date, pageNo, size, isDetail);

        try {
            Page<AccountManager.Commission> page = accountManager.getBill(date, uid, pageNo, size, isDetail);
            log.debug("用户{}的账单为：{}", uid, page);
            return BaseDTO.buildSuccess(page);
        } catch (Exception e) {
            log.error("获取用户{}的{}月账单出错", uid, date, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 查询账单详情
     *
     * @param id  流水ID
     * @param uid 用户ID
     * @return 佣金详情
     */
    @RequestMapping(value = "getCommission/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public BaseDTO<AccountManager.Commission> getCommission(@PathVariable("id") long id, @SessionAttribute("userId")
            long
            uid) {
        log.info("获取用户{}的{}的佣金详情", uid, id);

        try {
            AccountManager.Commission commission = accountManager.getCommission(id, uid);
            log.debug("用户{}的佣金{}详情为：{}", uid, id, commission);
            return BaseDTO.buildSuccess(commission);
        } catch (Exception e) {
            log.error("获取用户{}的{}的佣金详情出错", uid, id, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 查询用户实名认证状态
     *
     * @param uid 用户ID
     * @return 返回1表示未申请认证，返回2表示申请认证未审核，返回3表示实名认证审核未通过，返回4表示实名认证审核已通过，
     * 返回5表示未知状态
     */
    @RequestMapping(value = "isReal", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public BaseDTO<Map<String, Object>> isReal(@SessionAttribute("userId") long uid) {
        log.info("获取用户{}实名认证状态", uid);

        try {
            UserReal userReal = accountManager.isReal(uid);

            log.debug("用户{}的实名认证状态为：{}", uid, userReal);
            int status = accountManager.checkUserReal(userReal);
            log.debug("用户{}的实名认证状态转换为：{}", uid, status);
            Map<String, Object> map = new HashMap<>();
            BaseDTO<Map<String, Object>> dto = BaseDTO.buildSuccess(map);
            map.put("status", status);
            map.put("max", AccountManager.MAXCERT);
            map.put("header", status == 4 ? noticeManager.getUserHeader(uid) : null);
            if (userReal != null) {
                map.put("count", userReal.getCommitCount());
                map.put("card", userReal.getIdNumber());
                map.put("name", userReal.getRealName());
                map.put("quick", AccountManager.isQuck(userReal.getCommitCount()));
                dto.setMessage(status == 3 ? userReal.getRemark() : null);
            } else {
                map.put("count", 0);
                map.put("card", 0);
                map.put("name", "");
                map.put("quick", true);
            }
            return dto;
        } catch (Exception e) {
            log.error("获取用户{}的实名认证状态出错", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 申请实名认证
     *
     * @param uid      用户id
     * @param name     真实姓名
     * @param idcard   身份证号
     * @param type     身份证类型，00表示二代身份证，01表示临时身份证
     * @param imgFront 身份证人像面照片URL
     * @param imgCon   身份证国徽面照片URL
     * @param code     短信验证码
     * @return 返回true表示申请成功，返回false表示失败
     */
    @RequestMapping(value = "applyCertification", method = {RequestMethod.POST})
    @ResponseBody
    public BaseDTO<Integer> applyCertification(@SessionAttribute("userId") long uid, @RequestParam("name") String name,
                                               @RequestParam("idcard") String idcard, @RequestParam("type") String
                                                       type, @RequestParam("imgFront") String imgFront,
                                               @RequestParam("imgCon") String imgCon, @RequestParam("code") String
                                                       code) {
        log.info("用户{}申请实名认证，参数为：{}:{}:{}:{}:{}:{}", uid, name, idcard, type, imgFront, imgCon, code);

        try {
            int success = accountManager.applyCertification(uid, name, idcard, type, imgFront, imgCon, code);
            log.debug("用户{}申请实名认证状态为：{}", uid, success);
            return BaseDTO.buildSuccess(success);
        } catch (Exception e) {
            log.error("获取用户{}的实名认证状态出错", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 发送验证码
     *
     * @param uid 用户UID
     * @return 返回发送结果（具体结果参照短信服务）
     */
    @RequestMapping(value = "sendSms", method = {RequestMethod.GET})
    @ResponseBody
    public BaseDTO<Map<String, Object>> sendSms(@SessionAttribute("userId") long uid) {
        log.info("用户{}申请发送验证码", uid);
        try {
            return BaseDTO.buildSuccess(accountManager.sendCashApplySms(uid));
        } catch (Exception e) {
            log.error("用户{}申请发送验证码", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 发送实名认证验证码（快速通道）
     *
     * @param uid 用户ID
     * @return 发送结果
     */
    @RequestMapping(value = "sendCertSms", method = {RequestMethod.GET})
    @ResponseBody
    public BaseDTO<Map<String, Object>> sendCertSms(@SessionAttribute("userId") long uid) {
        log.info("用户{}申请发送实名认证验证码", uid);
        try {
            return BaseDTO.buildSuccess(accountManager.sendCertApply(uid));
        } catch (Exception e) {
            log.error("用户{}申请发送实名认证验证码失败", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 发送实名认证验证码（人工通道）
     *
     * @param uid 用户ID
     * @return 发送结果
     */
    @RequestMapping(value = "sendCertApplyByHuman", method = {RequestMethod.GET})
    @ResponseBody
    public BaseDTO<Map<String, Object>> sendCertApplyByHuman(@SessionAttribute("userId") long uid) {
        log.info("用户{}申请发送实名认证验证码", uid);
        try {
            return BaseDTO.buildSuccess(accountManager.sendCertApplyByHuman(uid));
        } catch (Exception e) {
            log.error("用户{}申请发送实名认证验证码失败", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 申请实名认证
     *
     * @param uid  用户ID
     * @param card 身份证号
     * @param name 真实姓名
     * @param code 验证码
     * @return 返回0表示认证成功，返回1表示认证失败，返回2表示当前实名认证次数过多，请走人工通道，返回3表示参数错误，返
     * 回4表示用户已经申请实名认证，返回5表示验证码错误
     */
    @RequestMapping(value = "applyCert", method = {RequestMethod.POST})
    @ResponseBody
    public BaseDTO<Integer> applyCert(@SessionAttribute("userId") long uid, @RequestParam("card") String card,
                                      @RequestParam("name") String name, @RequestParam("code") String code) {
        log.info("用户{}提交实名认证，身份证号为：{}，名字为：{}", uid, card, name);
        return BaseDTO.buildSuccess(accountManager.applyCert(uid, card, name, code));
    }

    /**
     * 提现申请
     *
     * @param uid           用户ID
     * @param price         提现金额
     * @param cashMode      提现方式，00银行卡，01支付宝
     * @param alipayAccount 支付宝账户
     * @param bankCard      银行卡号
     * @param bankName      银行名称
     * @param code          验证码
     * @return 申请状态，返回0成功，返回1参数错误，返回2当前不支持提现（没有相关的系统配置），返回3表示提
     * 现金额小于系统允许最小提现金额，返回4表示用户钱包余额不足，返回5表示验证码错误
     */
    @RequestMapping(value = "cashApply", method = {RequestMethod.POST})
    @ResponseBody
    public BaseDTO<Integer> cashApply(@SessionAttribute("userId") long uid, double price, String cashMode, String
            alipayAccount, String bankCard, String bankName, @RequestParam("code") String code) {
        log.info("用户{}提交提现申请", uid);
        try {
            int result = accountManager.cashApply(uid, price, cashMode, alipayAccount, bankCard, bankName, code);
            BaseDTO<Integer> dto = BaseDTO.buildSuccess(result);
            log.debug("用户{}的提现申请结果为：{}", uid, result);
            return dto;
        } catch (Exception e) {
            log.error("用户{}提交提现申请失败", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 获取当前用户的绑定手机号
     *
     * @param uid 用户UID
     * @return 当前用户绑定手机号
     */
    @RequestMapping(value = "getPhone", method = {RequestMethod.GET})
    @ResponseBody
    public BaseDTO<String> getPhone(@SessionAttribute("userId") long uid) {
        log.debug("用户{}获取手机号", uid);
        try {
            return BaseDTO.buildSuccess(accountManager.getPhone(uid));
        } catch (Exception e) {
            log.error("用户{}获取手机号失败", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 获取当前用户的真实姓名
     *
     * @param uid 当前用户的uid
     * @return 当前用户的真实姓名
     */
    @RequestMapping(value = "getRealName", method = {RequestMethod.GET})
    @ResponseBody
    public BaseDTO<String> getRealName(@SessionAttribute("userId") long uid) {
        log.debug("用户{}获取实名认证姓名", uid);
        try {
            return BaseDTO.buildSuccess(accountManager.getRealName(uid, true));
        } catch (Exception e) {
            log.error("用户{}获取实名认证姓名失败", uid, e);
            return BaseDTO.buildError();
        }
    }

    /**
     * 获取最小提现金额
     *
     * @param uid 用户ID
     * @return 最小提现金额
     */
    @RequestMapping(value = "getMinCashout", method = {RequestMethod.GET})
    @ResponseBody
    public BaseDTO<AccountManager.CashRuleDTO> getMinCashout(@SessionAttribute("userId") long uid) {
        log.debug("用户获取最小提现金额");
        try {
            return BaseDTO.buildSuccess(accountManager.getMinCashout(uid));
        } catch (Exception e) {
            log.error("用户获取最小提现金额失败", e);
            return BaseDTO.buildError();
        }
    }
}
